<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <div class="homework-info">
      <div class="work-tag">作业</div>
      <div class="work-content">
        <h3>{{ workInfo.title }}</h3>
        <div class="work-meta">
          <span class="work-type">{{ workInfo.type === 1 ? '个人作业' : '小组作业' }}</span>
          <span class="work-time">提交截止时间：{{ workInfo.endTime }}</span>
          <span class="work-score">{{ workInfo.score }}分</span>
          <span class="work-status">{{ formatWorkStatus(workInfo.status) }}</span>
        </div>
        <div class="work-desc">{{ workInfo.content }}</div>
        
        <!-- 更多按钮 -->
        <!-- 更多按钮部分修改 -->
          <el-dropdown trigger="click" class="more-actions">
            <span class="el-dropdown-link">
              ...更多<i class="el-icon-arrow-down"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <!-- 添加判断条件：未发布才显示编辑选项 -->
                <el-dropdown-item 
                  @click="handleEdit"
                >编辑</el-dropdown-item>
                <el-dropdown-item>移动到章节</el-dropdown-item>
                <el-dropdown-item>保存到课程区</el-dropdown-item>
                <!-- 添加判断条件：未发布才显示删除选项 -->
                <el-dropdown-item 
                  @click="handleDelete" 
                  class="danger"
                >删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
      </div>
  
  <!-- 编辑作业对话框 -->
<el-dialog
  title="编辑作业"
  v-model="dialogVisible"
  width="600px"
>
<!-- 导入作业按钮 -->
<div class="import-btn">
  <el-button type="primary" @click="handleImport">
    导入作业
  </el-button>
  <div v-if="selectedFile" class="selected-file">
    <span class="file-name">已选择文件: {{ selectedFile.name }}</span>
    <el-icon class="delete-icon" @click="handleRemoveFile">
      <Close />
    </el-icon>
  </div>
</div>

  <!-- 隐藏的文件输入框 -->
  <input
  ref="fileInput"
  type="file"
  style="display: none"
  accept=".doc,.docx,.pdf,.jpg,.jpeg,.png,.gif"  
  @change="onFileChange"
  />
  <el-form :model="editForm" label-width="100px">
    <el-form-item label="作业类型" required>
      <el-radio-group v-model="editForm.type">
        <el-radio :label="1">个人作业</el-radio>
        <el-radio :label="2">小组作业</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="作业标题" required>
      <el-input v-model="editForm.title" maxlength="70" show-word-limit></el-input>
    </el-form-item>
    <el-form-item label="内容">
      <el-input type="textarea" v-model="editForm.content" rows="4"></el-input>
    </el-form-item>
    <el-form-item label="活动类型标签">
      <el-input v-model="editForm.activity" :maxlength="10" show-word-limit></el-input>
    </el-form-item>
    <el-form-item label="应用于章节">
  <el-select v-model="editForm.chapterId" placeholder="请选择章节">
    <el-option label="课前" :value="1"></el-option>
    <el-option label="课中" :value="2"></el-option>
    <el-option label="课后" :value="3"></el-option>
    <el-option label="期中" :value="4"></el-option>
    <el-option label="期末" :value="5"></el-option>
  </el-select>
</el-form-item>


    <el-form-item label="所属章节">
      <el-select v-model="editForm.section" placeholder="请选择"></el-select>
    </el-form-item>
    <el-form-item>
      <el-switch
        v-model="editForm.isPublishNow"
        active-text="是否立即发布"
      />
    </el-form-item>
    <el-form-item label="发布时间" v-if="!editForm.isPublishNow">
      <el-date-picker v-model="editForm.releaseTime" type="datetime"></el-date-picker>
    </el-form-item>
    <el-form-item label="截止时间" required>
      <el-date-picker v-model="editForm.endTime" type="datetime"></el-date-picker>
    </el-form-item>
    <el-form-item label="总分" required>
      <el-input-number v-model="editForm.score" :min="0" :max="100"></el-input-number>
     <el-switch
       v-model="editForm.isAllowOvertimeSubmission"
       :active-value="2"    
       :inactive-value="1"  
       class="ml-2"
       style="margin-left: 20px"
       active-text="到时禁止提交"
     />
   </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSave">确 定</el-button>
    </span>
  </template>
</el-dialog>
<work-comment :work-id="workInfo.id" />
    </div>
  </template>
  
  <script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { getWorkInfo, updateWork, uploadWorkFile, deleteWork } from '@/api/work.js'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { Close } from '@element-plus/icons-vue'  // 引入图标
import WorkComment from '@/components/WorkComment.vue'
import Storage from '@/utils/storage'

  const workId = Storage.getSession("workId");

 // 作业信息
const workInfo = reactive({
  id: 0,
  courseId: 0,
  type: 1,  // 1表示个人作业
  title: '',
  content: '',
  chapterId: null,
  createTime: '',
  releaseTime: '',
  endTime: '',
  status: 1,
  file: null,
  score: 0,
  process: 0,
  activity: '',
  isAllowOvertimeSubmission: 1,
  isShowScore: null
})

// 编辑表单数据
const editForm = reactive({
  type: 1,
  title: '',
  content: '',
  activity: '作业',
  chapterId: null,
  section: '',
  isPublishNow: true,
  releaseTime: '',
  endTime: '',
  score: 10,
  isAllowOvertimeSubmission: 1
})
// 添加选中文件的响应式变量
const selectedFile = ref(null)
// 添加文件输入框的引用
const fileInput = ref(null)
const dialogVisible = ref(false)
const loading = ref(false)

// 获取作业详情
  const fetchWorkDetail = async () => {
    try {
      loading.value = true
      const res = await getWorkInfo(workId)
      console.log(res);
      if (res.code === 200) {
        const date = new Date(res.data.endTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        res.data.endTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        Object.assign(workInfo, res.data)
      } else {
        ElMessage.error(res.message || '获取作业详情失败')
      }
    } catch (error) {
      console.error('获取作业详情错误:', error)
      ElMessage.error('获取作业详情失败')
    } finally {
      loading.value = false
    }
  }

// 判断作业是否已发布的计算属性
const isPublished = computed(() => {
  if (!workInfo.releaseTime) return false
  return new Date(workInfo.releaseTime) <= new Date()
})


// 格式化作业状态
// eslint-disable-next-line no-unused-vars
const formatWorkStatus = (status) => {
  const statusMap = {
    '1': '允许超时提交',
    '2': '不允许超时提交'
  }
  return statusMap[workInfo.isAllowOvertimeSubmission] || '未知状态'
}


// 修改 handleEdit 函数
// 修改 handleEdit 函数
const handleEdit = () => {
  // 添加发布状态检查
  if (isPublished.value) {
    ElMessage.warning('作业已发布，无法修改')
    return
  }

  Object.assign(editForm, {
    type: workInfo.type,
    title: workInfo.title,
    content: workInfo.content,
    activity: workInfo.activity,
    chapterId: workInfo.chapterId,
    section: workInfo.section,
    releaseTime: workInfo.releaseTime,
    endTime: workInfo.endTime,
    score: workInfo.score,
    isAllowOvertimeSubmission: workInfo.isAllowOvertimeSubmission,
    isPublishNow: false
  })
  dialogVisible.value = true
}

// 处理文件选择变化
const onFileChange = (e) => {
  const file = e.target.files[0]
  if (file) {
    selectedFile.value = file
  }
  e.target.value = '' // 清空input使其可以重复选择
}

// 处理导入按钮点击
const handleImport = () => {
  fileInput.value.click()
}

// 添加删除文件的处理函数
const handleRemoveFile = () => {
  selectedFile.value = null
}

// 修改保存处理函数
const handleSave = async () => {
  // 添加发布状态检查
  if (isPublished.value) {
    ElMessage.warning('作业已发布，无法修改')
    return
  }
  try {
    loading.value = true
    
    let fileUrl = null
    // 如果有选择文件，先上传文件
    if (selectedFile.value) {
      const formData = new FormData()
      // 确保使用正确的字段名，这里使用 'file'
      formData.append('file', selectedFile.value)
      
      // 添加其他可能需要的字段
      formData.append('workId', workId)
      
      const uploadRes = await uploadWorkFile(workId, formData)
      if (uploadRes.code !== 200) {
        throw new Error(uploadRes.message || '文件上传失败')
      }
      fileUrl = uploadRes.data // 根据后端返回格式调整
    }

    // 构建更新参数
    const params = {
      id: workId,
      courseId: workInfo.courseId,
      ...editForm,
      releaseTime: editForm.isPublishNow ? new Date() : editForm.releaseTime,
      file: fileUrl // 添加文件URL
    }

    // 验证必填字段
    if (!params.title?.trim()) {
      throw new Error('请输入作业标题')
    }
    if (!params.endTime) {
      throw new Error('请选择截止时间')
    }
    if (params.score === undefined || params.score < 0) {
      throw new Error('请设置有效的分数')
    }

    const res = await updateWork(workId, params)
    if (res.code === 200) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      selectedFile.value = null // 清空已选文件
      workInfo.isAllowOvertimeSubmission = editForm.isAllowOvertimeSubmission
      await fetchWorkDetail() // 刷新作业详情
    } else {
      throw new Error(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存作业错误:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    loading.value = false
  }
}

// 添加删除处理函数
const handleDelete = async () => {
  try {
    // eslint-disable-next-line no-undef
    await ElMessageBox.confirm(
      '确定要删除这个作业吗？删除后将无法恢复',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const res = await deleteWork(workId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 这里可以添加删除后的处理，比如跳转到列表页面
      // router.push('/work/list')
      window.location.reload(); // 刷新整个页面
    } else {
      throw new Error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除作业错误:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 组件挂载时获取作业详情
onMounted(() => {
  fetchWorkDetail()
})
</script>
  
  <style scoped>
  .homework-info {
    padding: 20px;
    position: relative;
  }
  
  .work-tag {
    display: inline-block;
    background-color: #48c9b0;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  }
  
  .work-meta {
    margin: 10px 0;
    color: #666;
    font-size: 14px;
  }
  
  .work-meta > span {
    margin-right: 20px;
  }
  
  .more-actions {
    position: absolute;
    right: 20px;
    top: 20px;
    cursor: pointer;
  }
  
  .dialog-footer {
    padding: 20px 0;
    text-align: right;
  }

  /* style 部分添加 */
.selected-file {
  display: inline-flex;
  align-items: center;
  margin-left: 10px;
}

.file-name {
  margin-right: 8px;
}

.delete-icon {
  color: #909399;
  cursor: pointer;
  font-size: 16px;
  transition: color 0.2s;
}

.delete-icon:hover {
  color: #f56c6c;
}

/* 添加删除按钮的样式 */
.danger {
  color: #f56c6c;
}

  </style>
  